package com.net.shop.car.manager.api.volley;

import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.net.shop.car.manager.App;
import com.net.shop.car.manager.utils.LogUtils;

/**
 * @author Deve xu
 * 
 */
public abstract class VolleyListenerImpl<T extends Response> implements
		VolleyListener {

	public static final int VOLLEY_INNER_ERROR = -1;
	public static final int RESPONSE_STR_FROMAT_ERROR = -2;
	/**
	 * 
	 */
	private T mResponse;

	/**
	 * 
	 * @param response
	 *            Response
	 */
	public VolleyListenerImpl(T t) {
		this.mResponse = t;
	}

	@Override
	public void onError(VolleyError error) {
		LogUtils.e("Volley error " + error.getMessage());
		mResponse.setErrorMsg("网络连接失败");
	}

	@Override
	public void onParse(String response) {
		try {
			LogUtils.i("response data :" + response);
			JSONObject jsonObject = new JSONObject(response);
			String flag = jsonObject.getString("flag");
			if (flag != null && flag.equals("success")) {
				this.mResponse.setSuccess(true);
			}
			if (this.mResponse.isSuccess()) {
				String contentTag = this.mResponse.getContentTag();
				if (!TextUtils.isEmpty(contentTag)) {
					this.mResponse.parseContent(jsonObject
							.getString(contentTag));
				}
				String[] contentTags = this.mResponse.getContentTags();
				if (contentTags != null && contentTags.length > 0) {
					for (int i = 0; i < contentTags.length; i++) {
						this.mResponse.parseContent(jsonObject
								.getString(contentTags[i]),i);
					}
				}
			} else {
				String errorCode;
				try {
					errorCode = jsonObject.getString("error");
					this.mResponse.setErrorMsg(errorCode);
				} catch (JSONException e) {
					this.mResponse.setErrorMsg("返回字段错误");
				}
			}
		} catch (JSONException e) {
			LogUtils.e(e.getMessage());
			this.mResponse.setErrorMsg("返回字段错误");
		}
	}

	@Override
	public void onResponse() {
		deleveryResponse(mResponse);
		if (!mResponse.isSuccess()) {
			App.i().showToast(mResponse.getErrorMsg());
	}
	}

	public abstract void deleveryResponse(T response);
}
